package cn.tedu.boot02.controller;

import cn.tedu.boot02.entity.Product;
import cn.tedu.boot02.util.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import static com.alibaba.druid.sql.parser.Token.FROM;

@RestController
public class ProductController {
    @RequestMapping("/insert")
    public String insert(Product product){
        System.out.println("product = " + product);

        try (Connection conn = DBUtil.getConnection()){
            String sql = "INSERT INTO product VALUES(NULL,?,?,?)";
            //创建执行SQL语句的对象
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换掉里面的？
            ps.setString(1,product.getTitle());
            ps.setDouble(2,product.getPrice());
            ps.setInt(3,product.getNum());
            //执行SQL语句
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return "添加完成!";
    }
    @RequestMapping("/select")
    public String select(){
        ArrayList<Product>list = new ArrayList<>();
        try(Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM product";

                PreparedStatement ps = conn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();

            while (true) {
                Product product = new Product();
                product.setId(rs.getInt(1));
                product.setTitle(rs.getString(2));
                product.setPrice(rs.getDouble(3));
                product.setNum(rs.getInt(4));
                list.add(product);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list.toString();
    }
}
